package com.xinxing.learning.security.controller;

import com.xinxing.learning.security.entity.User;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/hello")
public class AuthorizeMethodController {

    // @PreAuthorize("hasRole('admin') and authentication.name == 'root'") // 验证角色
    @PreAuthorize("hasAuthority('read_info')") // 验证权限
    @GetMapping
    public String hello() {
        return "security authorize hello";
    }

    @PreAuthorize("authentication.name == #name")
    @GetMapping("/name")
    public String name(String name) {
        return "security authorize name " + name;
    }

    @PreFilter(value = "filterObject.id % 2!=0", filterTarget = "users") // filterTarget 过滤的参数 必须是 数组 或者 集合
    @PostMapping("/users")
    public void addUsers(@RequestBody List<User> users) {
        users.stream().forEach(System.out::println);
    }

    @PostAuthorize("returnObject.id == 1")
    @GetMapping("/userId")
    public User getUserById(long id) {
        return new User(id, "blr");
    }

    @PostFilter("filterObject.id%2==0")
    @GetMapping("/lists")
    public List<User> getAll() {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User(i, "name" + i);
            users.add(user);
        }
        return users;
    }

    @Secured("ROLE_admin") // 只能判断角色
    @GetMapping("/secured")
    public User getUserByUsername() {
        return new User(99, "secured");
    }

    @Secured({"ROLE_admin", "ROLE_user"}) // 具有其中一个角色即可
    @GetMapping("/username")
    public User getUserByUsername2(String username) {
        return new User(99, username);
    }

    @PermitAll // 都放行
    @GetMapping("/permitAll")
    public String permitAll() {
        return "permitAll";
    }

    @DenyAll // 都拒绝
    @GetMapping("/denyAll")
    public String denyAll() {
        return "denyAll";
    }

    @RolesAllowed({"ROLE_admin", "ROLE_user"}) // 具有其中给一个角色即可
    @GetMapping("/rolesAllowed")
    public String rolesAllowed() {
        return "rolesAllowed";
    }
}
